import "dart:convert";

import "package:ct_pa_majordomo/config/theme_vars.dart";
import "package:ct_pa_majordomo/pages/device/lock/api.dart";
import "package:ct_pa_majordomo/pages/widgets/menu_block.dart";
import "package:ct_pa_majordomo/state/common.dart";
import "package:ct_pa_majordomo/utils/stacker.dart";
import "package:ct_pa_majordomo/widgets/button/tap_container.dart";
import "package:ct_pa_majordomo/widgets/divider/solid_divider.dart";
import "package:ct_pa_majordomo/widgets/normal_scaffold/index.dart";
import "package:flutter/cupertino.dart";
import "package:flutter/material.dart";
import "package:flutter_easyloading/flutter_easyloading.dart";
import "package:provider/provider.dart";
import "package:ttlock_flutter/ttlock.dart";

class PwdManage extends StatefulWidget {
  Map info;
  PwdManage({super.key, required this.info});

  @override
  State<StatefulWidget> createState() => _PwdManageState();

}

class _PwdManageState extends State<PwdManage> {

  final Map _params = {};

  void _refreshLockInfo () {
    lockApi.getLockInfo(int.parse(widget.info["lockId"])).then((res) {
      if (mounted) {
        Provider.of<CommonState>(context, listen: false).setLockInfo(res["data"] ?? {});
        Map lockInfo = jsonDecode(res["data"]["lockInfo"]) ?? {};
        Provider.of<CommonState>(context, listen: false).setLockInfo(lockInfo);
      }
    });
  }

  // 修改密码
  void _editPwd({
    required BuildContext context,
    required String value,
    ValueChanged<String>? onChange,
  }) async {
    String textValue = value;
    showDialog(
        context: context,
        builder: (BuildContext context) {
          return Dialog(
            shape: const RoundedRectangleBorder(
              borderRadius: BorderRadius.all(Radius.circular(10)),
            ),
            child: ListView(
              shrinkWrap: true,
              children: [
                const Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Padding(
                      padding: EdgeInsets.symmetric(vertical: 10),
                      child: Text("修改密码", style: TextStyle(fontSize: 18),),
                    ),
                  ],
                ),
                Padding(
                  padding: const EdgeInsets.symmetric(horizontal: 10),
                  child: TextFormField(
                    autofocus: true,
                    decoration: const InputDecoration(
                      hintText: "请输入",
                      border: InputBorder.none,
                    ),
                    initialValue: textValue,
                    onChanged: (val) {
                      textValue = val;
                    },
                  ),
                ),
                const SolidDivider(),
                SizedBox(
                  height: 50,
                  child: Row(
                    children: [
                      Expanded(
                        child: TextButton(
                          onPressed: () {
                            Navigator.of(context).pop();
                          },
                          child: const Text("取消", style: TextStyle(color: ThemeVars.colorTextTer),),
                        ),
                      ),
                      const SolidDivider(direction: Axis.vertical,),
                      Expanded(
                        child: TextButton(
                            onPressed: () async {
                              if (textValue.isEmpty) return;
                              EasyLoading.show();
                              try {
                                await lockApi.updateAdminPwd(int.parse(widget.info["lockId"]), {
                                  "adminPasscode": textValue,
                                  "changeType": 2,
                                });
                                if (onChange != null) onChange(textValue);
                                Stacker.pop();
                                EasyLoading.showSuccess("密码修改成功");
                                _refreshLockInfo();
                                return;
                              } catch (e) {
                                // 错误提示
                              }

                              TTLock.modifyAdminPasscode(textValue, widget.info["lockData"], () {
                                lockApi.updateAdminPwd(int.parse(widget.info["lockId"]), {
                                  "adminPasscode": textValue,
                                  "changeType": 1,
                                }).then((res) {
                                  if (onChange != null) onChange(textValue);
                                  Stacker.pop();
                                  EasyLoading.showSuccess("密码修改成功");
                                  _refreshLockInfo();
                                });
                              }, (code, error) {
                                print("$code $error");
                              });
                            },
                            child: const Text("确定")
                        ),
                      ),
                    ],
                  ),
                )
              ],
            ),
          );
        }
    );
  }

  @override
  void initState() {
    Map lockInfo = Provider.of<CommonState>(context, listen: false).lockInfo ?? {};
    setState(() {
      _params["password"] = lockInfo["noKeyPwd"];
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return NormalScaffold(
      title: "管理页开锁密码",
      child: ListView(
        padding: const EdgeInsets.all(ThemeVars.paddingPage),
        children: [
          MenuBlock(
            items: [
              MenuBlockItem(
                text: "密码",
                suffix: Consumer<CommonState>(builder: (context, state, child) {
                  return Text(state.lockInfo?["noKeyPwd"], style: const TextStyle(color: ThemeVars.colorTextTer),);
                }),
                onTap: () {
                  _editPwd(
                    context: context,
                    value: _params["password"],
                    onChange: (value) => setState(() {
                      _params["password"] = value;
                    }),
                  );
                },
              ),
            ]
          ),
          const SizedBox(height: 12,),
          const Text("如果你在锁上修改过密码，锁内实际有效的密码与这里显示的可能不同。", style: TextStyle(fontSize: 12, color: ThemeVars.colorTextTer),),
          TapContainer(
            onTap: () {
              // Provider.of<CommonState>(context, listen: false).setLockInfo({...widget.info, "lockAlias": "草泥马"});
              EasyLoading.show();
              TTLock.getAdminPasscode(widget.info["lockData"], (password) {
                /// 更新管理员密码
                lockApi.updateAdminPwd(int.parse(widget.info["lockId"]), {
                  "adminPasscode": password,
                  "changeType": 1,
                }).then((res) {
                  EasyLoading.showSuccess("管理员密码上传成功");
                  _refreshLockInfo();
                });
              }, (errorCode, error) {
                EasyLoading.showError("$errorCode: $error");
              });
            },
            textStyle: const TextStyle(color: ThemeVars.colorPrimary,),
            child: const Text("上传锁内管理员密码"),
          ),
        ],
      ),
    );
  }

}